package cn.itcast.n4_共享模型_管程;

import lombok.extern.slf4j.Slf4j;
import org.openjdk.jol.info.ClassLayout;

import java.util.Vector;
import java.util.concurrent.locks.LockSupport;

@Slf4j(topic = "c.Test19_批量撤销")
public class Test19_批量撤销 {
    static Thread t1, t2, t3;

    public static void main(String[] args) throws InterruptedException {
        Thread.sleep(4000);
        Vector<Dog> list = new Vector<>();
        int loopNumber = 39;
        t1 = new Thread(() -> {
            for (int i = 0; i < loopNumber; i++) {
                Dog d = new Dog();
                list.add(d);
                synchronized (d) {
                    log.debug(i + "\t" + ClassLayout.parseInstance(d).toPrintableSimple());
                }
            }
            LockSupport.unpark(t2);
        }, "t1");
        t1.start();
        t2 = new Thread(() -> {
            LockSupport.park();
            log.debug("===============> ");
            for (int i = 0; i < loopNumber; i++) {
                Dog d = list.get(i);
                log.debug(i + "\t" + ClassLayout.parseInstance(d).toPrintableSimple());
                synchronized (d) {
                    //前19个也就是0-18变成了轻量级锁，解锁后变成正常
                    //后面的19-38偏向t2了
                    log.debug(i + "\t" + ClassLayout.parseInstance(d).toPrintableSimple());
                }
                log.debug(i + "\t" + ClassLayout.parseInstance(d).toPrintableSimple());
            }
            LockSupport.unpark(t3);
        }, "t2");
        t2.start();
        t3 = new Thread(() -> {
            LockSupport.park();
            log.debug("===============> ");
            for (int i = 0; i < loopNumber; i++) {
                Dog d = list.get(i);
                log.debug(i + "\t" + ClassLayout.parseInstance(d).toPrintableSimple());
                synchronized (d) {
                    //前19个会变成轻量级锁
                    //后面20-38的需要撤销t2偏向锁
                    log.debug(i + "\t" + ClassLayout.parseInstance(d).toPrintableSimple());
                }
                log.debug(i + "\t" + ClassLayout.parseInstance(d).toPrintableSimple());
            }
        }, "t3");
        t3.start();
        t3.join();
        //其实相当于每个对象都进行了撤销偏向了0-38,也就是39次
        log.debug(ClassLayout.parseInstance(new Dog()).toPrintableSimple());
    }
}
